
/**
** \file       compound_list.c
**
** \brief      this function parse the compound_list rule
**
** \author     Ben M'rad Hanna, Laterem Hamza, Boillot Ulysse,
**             De Olivera Guillaume and Nguyen Viet Dung
**
** \version    1.0
**
** \date       28 Novembre 2010
**
*/

#include "rules.h"

static s_cmpdlist        *init(s_cmpdlist                       *cmpdl)
{
  cmpdl->andor = calloc(1, sizeof (s_andor));

  return (cmpdl);
}

int                     keyword(char                            *str)
{
  int                   i = 0;

  for (i = 0; i < SIZE2; ++i)
  {
    if (strcmp(g_data->lexer->token->id, str) == 0)
      break;
  }

  if (i != SIZE2)
    return (0);

  return (1);
}

static s_cmpdlist       *verif(struct andor                     *last,
                               s_cmpdlist                       *cmpdl)
{
  if (last != NULL)
  {
    free(last->next);
    last->next = NULL;
  }
  else
  {
    free(last);
    last = NULL;
  }

  return (cmpdl);
}

static s_cmpdlist       *rule_compound_list1(s_cmpdlist         *cmpdl,
                                             struct andor       *tmp_andor)
{
  struct andor          *last = NULL;

  tmp_andor = cmpdl->andor;

  while ((g_data->lexer != NULL) &&
         (!strcmp(g_data->lexer->token->id, ";") ||
          !strcmp(g_data->lexer->token->id, "&") ||
          !strcmp(g_data->lexer->token->id, "\n")))
  {
    g_data->lexer = g_data->lexer->next;

    if (keyword(g_data->lexer->token->id) == 0)
      return (verif(last, cmpdl));

    while ((g_data->lexer != NULL) && (!strcmp(g_data->lexer->token->id, "\n")))
      g_data->lexer = g_data->lexer->next;

    if (rule_and_or(tmp_andor) == NULL)
      {
	free(last->next);
	last->next = NULL;
	return (cmpdl);
      }
  }

  return (cmpdl);
}

s_cmpdlist              *rule_compound_list(s_cmpdlist          *cmpdl)
{
  struct andor		*tmp_andor = NULL;

  if (g_data->lexer == NULL)
    return (NULL);

  while ((g_data->lexer != NULL) && (!strcmp(g_data->lexer->token->id, "\n")))
    g_data->lexer = g_data->lexer->next;

  cmpdl = init(cmpdl);

  if (rule_and_or(cmpdl->andor) == NULL)
  {
    free(cmpdl->andor);
    cmpdl->andor = NULL;

    return (NULL);
  }

  cmpdl = rule_compound_list1(cmpdl, tmp_andor);
  return (cmpdl);
}
